# Copyright (c) 2005,2006,2007 Dynamic Solutions Inc. (support@dynamic-solutions.com)
#
# This file is part of DataZoomer.
#
# DataZoomer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# DataZoomer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


from zoom import zoomer
import os
import dzutil, dzpage

def render(controller=zoomer.webvars.con or None,action=zoomer.webvars.action or None,text=None,inline=None,template=None,partial=None,path=None,values=None,object=None,objects=None,separator=None):

    def module_name(controller,action):
        if action and controller and os.path.exists('%s_%s.txt' % (controller,action)):
            return '%s_%s' % (controller,action)
        elif controller and os.path.exists('%s_index.txt' % (controller)):
            return controller+'_index'
        elif action and os.path.exists('%s.txt' % (action)):
            return action
        else:
            return 'index'

    def load_template(filename):
        f = open(filename,'rb')
        t = f.read()
        f.close()
        return t

    def params(**kv):
        p = {}
        for k in kv:
            if kv[k]:
                p[k] = kv[k]
        return p

    def handle(*args,**kv):
        if args[0]=='action':
            p = params(con=controller,action=args[1],key=zoomer.webvars.key)
            page.actions.append(dzutil.link_to(args[2],**p))
        elif args[0]=='a':
            return dzutil.link_to(args[2],action=args[1])
            #return '(%s,%s)' % (repr(args),repr(kv))
        else:
            print 'unable to handle',args,kv

    zoomer.debug('render called with %s'%dict(controller=controller,action=action))

    page = None

    if text:
        return text
        module_path = ''
    elif inline:
        tpl = inline
        module_path = ''
#        page = dzpage.Page()
#        if os.path.exists('app.css'):
#            page.APPCSS = open('app.css','r').read()
    elif template:
        tpl = load_template(template+'.txt')
        module_path = ''
    elif partial:
        tpl = load_template('_'+partial+'.txt')
        module_path = ''
    elif path:
        tpl = load_template(path)
        module_path = ''
    else:
        template_path = module_name(controller,action)+'.txt'
        if os.path.isfile(template_path):
            tpl = load_template(template_path)
            page = dzpage.Page()
            if os.path.exists('app.css'):
                page.APPCSS = open('app.css','r').read()
        else:
            tpl = 'Template "%s" missing' % template_path
        module_path = (controller or 'view') + '.py'
        #module_path = module_name(controller,action)+'.py'

    import dzfill
    import dzml

    if module_path and os.path.isfile(module_path):
        namespace = dict(values=values,object=object,objects=objects)
        execfile(module_path,namespace)
        view = namespace.get('result',None)
        result = dzfill.fill(dzml.dzml(tpl,callback=handle,view=view,form=1),view)
    elif values:
        result = dzfill.fill(tpl,values.get)
    elif object:
        result = dzfill.fill(dzml.dzml(tpl,callback=handle,form=1),object)
    elif objects:
        separator = separator or ''
        result = separator.join([dzfill.fill(tpl,obj=object) for object in objects])
    else:
        def blank(name):
            return ''
        result = dzfill.fill(dzml.dzml(tpl,callback=handle,form=1),blank)

    if page:
        page.content = result
        result = page
    return result

